package com.leyou.upload.service;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.upload.config.OSSProperties;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: ycs
 * Date: 2020/8/18
 * Time: 19:58
 * 文件上传业务层
 */
@Service
@Slf4j
public class UploadService {
    /*指定一个允许上传的图片的mime类型的集合*/
    private static List<String> ALLOW_IMAGE_TYPE = Arrays.asList("image/jpeg");
    public String uploadImageToNginx(MultipartFile file) {
        //获取上传图片的类型
        String contentType = file.getContentType();
        //判断图片类型是否正确
        if (!ALLOW_IMAGE_TYPE.contains(contentType)){
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        File serverFile = new File(LyConstants.IMAGE_PATH);
        BufferedImage bufferedImage =null;
        try {
           bufferedImage= ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        if (bufferedImage==null){
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }
        //唯一文件名
        String fileName= UUID.randomUUID().toString()+file.getOriginalFilename();
        //文件上传路径
        File uploadFile=new File(serverFile,fileName);
        //上传文件
        try {
            file.transferTo(uploadFile);
            return LyConstants.IMAGE_URL+fileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }
    @Autowired
    private OSSClient client;
    @Autowired
    private OSSProperties prop;

    /**
     * 文件上传阿里云
     *
     * @return
     */
    //阿里官方提供api
    public Map<String, Object> getOssSignature() {
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;

        } catch (Exception e) {
            System.out.println(e.getMessage());
            log.error("阿里云OSS获取签名失败！失败原因为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }
}
